package com.bjkcst.baselib.modbus;

import com.licheedev.modbus4android.ModbusCallback;
import com.licheedev.modbus4android.ModbusParam;
import com.licheedev.modbus4android.ModbusWorker;
import com.licheedev.modbus4android.param.TcpParam;
import com.serotonin.modbus4j.ModbusMaster;

/**
 * @author: zgx
 * @email: zhougaoxing@bjkcst.com
 * @date: 2023/02/14
 * @describe:
 */

public class ModbusManager extends ModbusWorker {

    private static final int MODBUS_TIME_OUT = 2000;


    /**
     * modbus tcp / modbus rtu over tcp/ip 连接初始化
     *
     * @param ip             ip
     * @param port           port
     * @param isEncapsulated 这个属性确定了协议帧是否是通过tcp封装的RTU结构，采用modbus tcp/ip时，要设为false, 采用modbus rtu over tcp/ip时，要设为true
     * @param callback       callback
     * @return ModbusManager
     */
    public synchronized ModbusManager initModbusTcp(String ip, int port, boolean isEncapsulated, ModbusCallback<ModbusMaster> callback) {

        if (isModbusOpened()) {
            return this;
        }
        //modbus tcp / modbus rtu over tcp/ip
        ModbusParam<TcpParam> tcpParam = TcpParam.create(ip, port)
                .setEncapsulated(isEncapsulated)
                .setKeepAlive(true)
                .setTimeout(MODBUS_TIME_OUT)
                .setRetries(0);

        // 先把原来的关掉
        closeModbusMaster();
        init(tcpParam, callback);
        return this;
    }
}
